ProjectEditWin = Ext.extend(Ext.Window, {
    initComponent: function() {
        this.width = 1000;
        this.height = 700;
        this.title = 'Новый проект';
        this.closeAction = 'hide';
        this.layout = 'border';
        this.modal = true;
        this.maximizable = true;
        this.mode = 'add';
        this.editRec = {};
        this.sheme_type = 0;

        this.hidden = { id: 0,contract_1_id:0,contract_2_id:0,contract_3_id:0,year:2010,transfer_costs: 0,additional_costs:0,gross_profit:0,effectiveness:0 };

        this.initDataStores();
        this.initEditForm();
        this.initContractEdit();

        this.items = [ this.EditForm, this.Contracts ];

        this.buttons = [
            { text:'Сохранить', scale: 'medium', icon: '/bres/img/butt_ico_24/accept-icon.png', handler: this.DataSave, scope: this },
            { text: 'Отменить', scale: 'medium', icon: '/bres/img/butt_ico_24/remove-icon.png', handler: function(){ this.hide();}, scope: this }
        ];

        //this.on('activate', function() { this.show(); this.hide(); } , this);

        ProjectEditWin.superclass.initComponent.call(this);
    },
    showWin: function(mod) {
        this.mode = mod;
        if(this.mode == 'add') {
            this.setTitle('Новый проект');
            this.buttons[0].setText('Создать проект');
            this.EditForm.getForm().reset();
            this.show();
            this.Contracts.setActiveTab(1);
            this.Contracts.setActiveTab(2);
            this.Contracts.setActiveTab(0);
            this.C1.ContractForm.getForm().reset();
            this.C2.ContractForm.getForm().reset();
            this.C3.ContractForm.getForm().reset();
            this.C1.PlanResset();
            this.C2.PlanResset();
            this.C3.PlanResset();
            this.C1.disable(); this.C2.disable(); this.C3.disable();
            
        } else {
            this.show();
            var data = this.editRec.data;
            this.setTitle('Форма редактирования проекта');
            this.buttons[0].setText('Сохранить изменения');
            this.EditForm.getForm().reset();
            this.sheme.setValue('sh'+data.Sheme_Type,true);
            this.brandsStore.baseParams = {client_id: data.Client_ID};
            this.brandsStore.ffData = data;
            this.brandsStore.load();

            this.C1.contract_id = data.Contract_1_ID;  this.C1.getContractData();
            this.C2.contract_id = data.Contract_2_ID;  this.C2.getContractData();
            this.C3.contract_id = data.Contract_3_ID;  this.C3.getContractData();

            //this.show();
            this.Contracts.setActiveTab(1);
            this.Contracts.setActiveTab(2);
            this.Contracts.setActiveTab(0);
        }
    },
    initDataStores: function() {
        this.smiStore = new Ext.data.JsonStore({
            autoLoad: true,
            url: 'main?action=getSMI',
            root: 'data',
            fields: ['actor_id', 'actor_name', 'actor_short_name' ]
        });
        this.mediaStore = new Ext.data.JsonStore({
            autoLoad: true,
            url: 'main?action=getMA',
            fields: ['actor_id', 'actor_name', 'actor_short_name' ],
            root: 'data',
            listeners: { scope: this,
                load: function() {
                    //var rec = new Ext.data.Record({ fields: ['actor_id', 'actor_name', 'actor_short_name' ] });
                    //rec.actor_id=0; rec.actor_name='-'; rec.actor_short_name ='-';
                    //this.mediaStore.add(rec);
                }
            }
        });
        this.baingStore = new Ext.data.JsonStore({
            autoLoad: true,
            url: 'main?action=getBA',
            root: 'data',
            fields: ['actor_id', 'actor_name', 'actor_short_name' ]
        });
        this.customsStore = new Ext.data.JsonStore({
            autoLoad: true,
            root: 'data',
            url: 'main?action=getCustoms',
            fields: ['actor_id', 'actor_name', 'actor_short_name' ]
        });
        this.brandsStore = new Ext.data.JsonStore({
            autoLoad: false,
            ffData: null,
            root: 'data',
            url: 'main?action=getClientsBrands',
            fields: ['brand_id', 'client_id', 'brand_name', 'brand_short_name', 'comment'],
            listeners: { scope: this,
                load: function() {
                    if(this.brandsStore.ffData) this.EditForm.getForm().setValues(this.brandsStore.ffData);
                    this.brandsStore.ffData = null;
                    this.sheme.fireEvent('change' );
                }
            }
        });
    },
    initEditForm: function() {
       var BrandsList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', fieldLabel: 'Бренд', emptyText: 'выбирете бренд',
            triggerAction: 'all', disabled: true, ffValue: 0, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'brand_id', store: this.brandsStore, valueField: 'brand_id', displayField: 'brand_name'
        }); this.BL = BrandsList;
        var ClientsList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', fieldLabel: 'Клиент', emptyText: 'выбирете клиента', triggerAction: 'all', disabled: true, submitValue : false,
            listClass: 'x-combo-list-small', hiddenName: 'client_id', store: this.customsStore, valueField: 'actor_id', displayField: 'actor_name',
            listeners: { scope: this,
                select: function(cb, rec, idx) {
                    this.brandsStore.baseParams = {client_id: rec.data.actor_id};
                    this.brandsStore.load();
                    this.C1.consignee_id = rec.data.actor_id;
                }
            }
        });

        var F_MediaList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', emptyText: 'выбирете МА', width: 250,
            triggerAction: 'all', disabled: true, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'ma_id', store: this.mediaStore, valueField: 'actor_id', displayField: 'actor_name',
            listeners: { scope: this,
                select: function(cb, rec, idx) {
                    if( this.sheme_type == 1) {
                        this.C1.provider_id = rec.data.actor_id;
                        this.C2.consignee_id = rec.data.actor_id;
                    }
                    if( this.sheme_type == 2) {
                        this.C1.provider_id = rec.data.actor_id;
                        this.C3.consignee_id = rec.data.actor_id;
                    }
                }
            }
        });

        var B_MediaList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', emptyText: 'выбирете МА', width: 245,
            triggerAction: 'all', disabled: true, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'ma_b_id', store: this.mediaStore, valueField: 'actor_id', displayField: 'actor_name'
        });

        var MediaList = {
            layout: 'column', fieldLabel: 'Медиа агенство',
            bodyStyle: 'border: none; background-color:#DFE8F6;', bodyBorder: false,
            items: [{
                    columnWidth:.45, //layout: 'form',  //width: 300,
                    bodyStyle: 'border: none; background-color:#DFE8F6;', bodyBorder: false,
                    items: [ F_MediaList ]
            },{
                    columnWidth:.135, //layout: 'form', //width: 100,
                    bodyStyle: 'border: none; background-color:#DFE8F6; text-align:right;padding:3px 10px 0 0;',  bodyBorder: false,
                    items: [ {xtype: 'label', text: 'Бенифициар:  ', width: 105} ]
            },{
                    columnWidth:.415, //layout: 'form', //width: 100,
                    bodyStyle: 'border: none; background-color:#DFE8F6; text-align:right;',  bodyBorder: false,
                    items: [ B_MediaList ]
            }]
        };

        var BaingList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', fieldLabel: 'Баинговое агентство', emptyText: 'выбирете БА',
            triggerAction: 'all', disabled: true, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'ba_id', store: this.baingStore, valueField: 'actor_id', displayField: 'actor_name',
            listeners: { scope: this,
                select: function(cb, rec, idx) {
                    if( this.sheme_type == 1) {
                        this.C2.provider_id = rec.data.actor_id;
                        this.C3.consignee_id = rec.data.actor_id;
                    }
                    if( this.sheme_type == 3) {
                        this.C1.provider_id = rec.data.actor_id;
                        this.C3.consignee_id = rec.data.actor_id;
                    }
                }
            }
        });
        var F_SmiList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', emptyText: 'выбирете СМИ', width: 250,
            triggerAction: 'all', disabled: true, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'smi_id', store: this.smiStore, valueField: 'actor_id', displayField: 'actor_name',
            listeners: { scope: this,
                select: function(cb, rec, idx) {
                    this.C3.provider_id = rec.data.actor_id;
                }
            }
        });
        var B_SmiList = new Ext.form.ComboBox({
            mode: 'local', anchor: '100%', emptyText: 'выбирете СМИ', width: 245,
            triggerAction: 'all', disabled: true, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'smi_b_id', store: this.smiStore, valueField: 'actor_id', displayField: 'actor_name'
        });
        var SmiList = {
            layout: 'column', fieldLabel: 'СМИ',
            bodyStyle: 'border: none; background-color:#DFE8F6;', bodyBorder: false,
            items: [{
                    columnWidth:.45, //layout: 'form',  //width: 300,
                    bodyStyle: 'border: none; background-color:#DFE8F6;', bodyBorder: false,
                    items: [ F_SmiList ]
            },{
                    columnWidth:.135, //layout: 'form', //width: 100,
                    bodyStyle: 'border: none; background-color:#DFE8F6; text-align:right;padding:3px 10px 0 0;',  bodyBorder: false,
                    items: [ {xtype: 'label', text: 'Бенифициар:  ', width: 105} ]
            },{
                    columnWidth:.415, //layout: 'form', //width: 100,
                    bodyStyle: 'border: none; background-color:#DFE8F6; text-align:right;',  bodyBorder: false,
                    items: [ B_SmiList ]
            }]
        };

        this.sheme =  new Ext.form.RadioGroup({
            columns: 1,
            items: [
                {boxLabel: 'Клиент -> МА -> БА -> СМИ', inputValue: '1', name: 'sheme_type', id: 'sh1'},
                {boxLabel: 'Клиент -> МА -> СМИ', inputValue: '2', name: 'sheme_type', id: 'sh2'},
                {boxLabel: 'Клиент -> БА -> СМИ', inputValue: '3', name: 'sheme_type', id: 'sh3'}
            ],
            listeners: { scope: this,
                change: function(ch, old_val, new_val) {
                    if( typeof this.sheme.getValue != 'function' ) {
                        var val = this.sheme.value;
                    } else {
                        if(this.sheme.getValue()) var val = this.sheme.getValue().inputValue;
                        else val = 0;
                    }
                    if( val) {
                        BrandsList.enable(); ClientsList.enable(); F_SmiList.enable(); B_SmiList.enable(); this.C1.enable(); this.C3.enable();
                        if(val == 1 || val[0] == 'sh1') {  F_MediaList.enable(); B_MediaList.enable();  BaingList.enable(); this.C1.setTitle('Клиент – Медиа агентство'); this.C2.setTitle('Медиа агентство – Баинговое агентство'); this.C3.setTitle('Баинговое агентство - СМИ'); this.C2.enable(); this.sheme_type = 1; }
                        if(val == 2 || val[0] == 'sh3') {  F_MediaList.enable(); B_MediaList.enable();  BaingList.disable(); BaingList.reset();  this.C2.disable();  this.sheme_type = 2;  this.C1.setTitle('Клиент – Медиа агентство'); this.C2.setTitle('-'); this.C3.setTitle('Медиа агентство - СМИ'); }
                        if(val == 3 || val[0] == 'sh3') {  F_MediaList.disable(); F_MediaList.reset(); B_MediaList.disable(); B_MediaList.reset(); BaingList.enable(); this.C2.disable();  this.sheme_type = 3;  this.C1.setTitle('Клиент – Баинговое агентство'); this.C2.setTitle('-'); this.C3.setTitle('Баинговое агентство - СМИ'); }
                    } else {
                        BrandsList.disable(); ClientsList.disable(); SmiList.disable(); B_SmiList.disable(); MediaList.disable(); BaingList.disable();
                        this.C1.disable(); this.C2.disable(); this.C3.disable();  this.sheme_type = 0;
                    }
                }
            }
        });
        this.ShemeSelector = new Ext.form.FieldSet({
            region: 'west',
            width: 220,
            margins: '3 3 3 3',
            height:250,
            labelWidth: 10,
            title: 'Схема рализации',
            items: [ this.sheme ]
        });
        this.Actors = new Ext.form.FieldSet({
            title: 'Участники',
            region: 'center',
            margins: '3 3 3 3',
            //heigth: 150,
            labelWidth: 130,
            labelPad: 10,
            items: [ ClientsList, BrandsList, MediaList, BaingList, SmiList ]
        });
        this.EditForm = new Ext.form.FormPanel({
           region: 'center',
           height: 600,
           border: false,
           layout: 'border',
           items: [ this.ShemeSelector, this.Actors,
               new Ext.form.Hidden({name:'id', originalValue: 0}),
               new Ext.form.Hidden({name:'contract_1_id', originalValue: 0}),
               new Ext.form.Hidden({name:'contract_2_id', originalValue: 0}),
               new Ext.form.Hidden({name:'contract_3_id', originalValue: 0}),
               new Ext.form.Hidden({name:'year', originalValue: 2010}),
               new Ext.form.Hidden({name:'transfer_costs', originalValue: 0}),
               new Ext.form.Hidden({name:'additional_costs', originalValue: 0}),
               new Ext.form.Hidden({name:'gross_profit', originalValue: 0}),
               new Ext.form.Hidden({name:'effectiveness', originalValue: 0})
           ]
        });
    },
    initContractEdit: function() {
        
        this.C1 = new Contract; this.C1.setTitle('Контраст1'); //sss = this.C1.PlanStore; ggg = this.C1.PlanGrid;
        this.C2 = new Contract; this.C2.setTitle('Контраст2');  //this.C2.disable();
        this.C3 = new Contract; this.C3.setTitle('Контраст3');

        this.Contracts = new Ext.TabPanel({
            height: 450,
            //title: 'Контракты',
            margins: '3 3 3 3',
            border: false,
            region: 'south',
            activeTab: 0,
            items: [ this.C1, this.C2, this.C3 ]

        });
    },
    getFormData: function(){
            var form = this.EditForm.getForm();
            return form.getValues();
    },
    DataSave: function() {

        var data = this.EditForm.getForm().getValues();
        var dataC1 = this.C1.getFormData();
        var dataC2 = this.C2.getFormData();
        var dataC3 = this.C3.getFormData();

        var isContract1 = false;
        var isContract2 = false;
        var isContract3 = false;
        var th = this;

        var createProject = function(th) {
            if( isContract1 && isContract2 && isContract3 ) {
                Ext.Ajax.request({
                    url: 'main?action=updateProject',
                    params: data,
                    scope: th,
                    callback: function(options, success, response) {
                        var ansv = Ext.decode(response.responseText);
                        if(ansv.sucsess) {
                            if(ansv.wbs_id) {
                                //rec.data.doc_id = ansv.doc_id;
                            }
                            projectsStore.load();
                        } else { error_mes('Ошибка',  ansv.error); }
                                        th.hide();
                    }
                });
            }
        };

        Ext.Ajax.request({
            url: 'main?action=updateContract',
            params: dataC1,
            scope: th,
            callback: function(options, success, response) {
                var ansv = Ext.decode(response.responseText);
                if(ansv.sucsess) {
                    data.contract_1_id = ansv.contract_id;
                    isContract1 = true;
                    createProject(th);
                } else { error_mes('Ошибка',  ansv.error); }
            }
        });
        if(dataC2.contract_summ) {
                Ext.Ajax.request({
                        url: 'main?action=updateContract',
                        params: dataC2,
                        scope: th,
                        callback: function(options, success, response) {
                                var ansv = Ext.decode(response.responseText);
                                if(ansv.sucsess) {
                                        data.contract_2_id = ansv.contract_id;
                                        isContract2 = true;
                                        createProject(th);
                                } else { error_mes('Ошибка',  ansv.error); }
                        }
                });
        } else isContract2 = true;
        Ext.Ajax.request({
                url: 'main?action=updateContract',
                params: dataC3,
                scope: th,
                callback: function(options, success, response) {
                        var ansv = Ext.decode(response.responseText);
                        if(ansv.sucsess) {
                                data.contract_3_id = ansv.contract_id;
                                isContract3 = true;
                                createProject(th);
                        } else { error_mes('Ошибка',  ansv.error); }
                }
        });




    }
});

